package cn.com.connected.common.aop;

import cn.com.connected.common.config.CurrentData;
import cn.com.connected.common.emnus.StatusType;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Aspect
@Component
public class InsertMapper {
    @Pointcut("execution(* cn.com.connected.mapper..*Mapper.insert*(..))")
    public void pointcut(){}

    @Order(1)
    @Before("pointcut()")
    public void handlerInsert(JoinPoint joinPoint)  throws Throwable{
        Object obj = joinPoint.getArgs()[0];
        try {


            Field[] fields = obj.getClass().getDeclaredFields();
            List<String> names = Arrays.stream(fields).map(field -> field.getName()).collect(Collectors.toList());

            //塞入默认创建时间
            if(names.contains("createTime")){
                setValue(obj,"createTime", new Date());
            }

            //塞入默认状态
            if(names.contains("status")){
                setValue(obj,"status", StatusType.t1.getValue());
            }

            //塞入创建人
            if(names.contains("createUserId") && CurrentData.getUser()!=null){
                setValue(obj,"createUserId", CurrentData.getMemberId());
            }
            if(names.contains("createUser") && CurrentData.getUser()!=null){
                setValue(obj,"createUser", CurrentData.getMemberId());
            }


        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void setValue(Object obj,String name,Object value)  throws Throwable{
        Method createTimeMethod = obj.getClass().getDeclaredMethod("set"+ StringUtils.capitalize(name), value.getClass());
        Object createTime = getValue(obj,"get"+StringUtils.capitalize(name));
        if (createTime==null){
            createTimeMethod.invoke(obj, value);
        }
    }

    /**
     * 反射对象的id
     *
     * @param t
     * @return
     */
    private Object getValue(Object t,String getAtr) {
        try {
            Method getValue = t.getClass().getDeclaredMethod(getAtr);
            Object o = getValue.invoke(t);
            return o;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
